<template>
  <div class="user-info-wrapper">
    <el-card shadow="hover" class="user-info-card">
      <div class="user-info-header">
        <div v-if="showImageAvatar">
          <img :src="curUser.avatar" class="user-avatar-square"/>
        </div>
        <div v-else class="user-avatar-square" :style="{backgroundColor: avatarBgColor}">
          <span class="avatar-text">{{ getAvatarText(curUser.userName) }}</span>
        </div>
        <el-select v-model="avatarBgColor" placeholder="选择头像背景色" class="avatar-color-select" @change="onAvatarColorChange">
          <el-option v-for="color in avatarColors" :key="color" :label="color" :value="color">
            <span :style="{background: color, display: 'inline-block', width: '20px', height: '20px', borderRadius: '50%'}"></span>
          </el-option>
        </el-select>
      </div>
      <el-divider></el-divider>
      <el-form label-position="top" label-width="100px" class="user-info-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="curUser.userName" :disabled="true" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="curUser.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="curUser.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学校">
              <el-input v-model="curUser.school" placeholder="请输入学校"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="curUser.gender" placeholder="请选择性别" style="width:100%">
                <el-option label="男" value="male"/>
                <el-option label="女" value="female"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日">
              <el-date-picker
                v-model="curUser.birthday"
                type="date"
                placeholder="请选择生日"
                style="width:100%"
                @change="onBirthdayChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="user-info-actions">
          <el-button type="primary" @click="saveUserInfo">保存</el-button>
          <el-button type="default" @click="showChangePwd = true">修改密码</el-button>
        </el-form-item>
        <el-dialog title="修改密码" :visible.sync="showChangePwd" width="400px" @close="resetPwdForm">
          <el-form :model="pwdForm" ref="pwdFormRef" label-width="100px">
            <el-form-item label="历史密码" prop="oldPassword" :rules="[{ required: true, message: '请输入历史密码', trigger: 'blur' }]">
              <el-input v-model="pwdForm.oldPassword" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword" :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]">
              <el-input v-model="pwdForm.newPassword" type="password" autocomplete="off" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="showChangePwd = false">取消</el-button>
            <el-button type="primary" @click="handleChangePassword">确定</el-button>
          </div>
        </el-dialog>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "UserInfo",
  data(){
    const user = JSON.parse(window.localStorage.getItem('user') || '{}');
    return{
      curUser: {
        userName: user.userName || '',
        email: user.email || '',
        avatar: user.avatar || '',
        phone: user.phone || '',
        school: user.school || '',
        gender: user.gender || '',
        birthday: user.birthday || ''
      },
      avatarBgColor: user.avatarBgColor || '#409EFF',
      avatarColors: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#1abc9c', '#e67e22', '#e74c3c', '#8e44ad'],
      showChangePwd: false,
      pwdForm: { oldPassword: '', newPassword: '' }
    }
  },
  computed: {
    showImageAvatar() {
      if (!this.curUser.avatar || this.curUser.avatar.trim() === '') return false;
      const defaultAvatars = [
        '/static/img/default.png',
        '/img/defaultImg.png',
        '/static/avatar/default.png',
        'default.png',
      ];
      return !defaultAvatars.includes(this.curUser.avatar.trim());
    }
  },
  mounted() {
    this.getCurUser();
  },
  methods: {
    onBirthdayChange(val) {
      // 选中日期后自动格式化为 'YYYY-MM-DD'
      if (val) {
        const dateObj = new Date(val);
        if (!isNaN(dateObj.getTime())) {
          const yyyy = dateObj.getFullYear();
          const mm = String(dateObj.getMonth() + 1).padStart(2, '0');
          const dd = String(dateObj.getDate()).padStart(2, '0');
          this.curUser.birthday = `${yyyy}-${mm}-${dd}`;
        }
      }
    },
    onAvatarColorChange() {
      // 切换颜色时强制只用字母头像
      this.curUser.avatar = '';
    },
    getCurUser() {
      let _this = this;
      this.$axios.get('/users/info').then(resp => {
        if (resp && resp.code === 200 && resp.data) {
          // 用后端返回的最新数据同步 curUser
          _this.curUser = {
            id: resp.data.userId || resp.data.id,
            userName: resp.data.username || resp.data.userName || '',
            email: resp.data.email || '',
            avatar: resp.data.avatar || '',
            phone: resp.data.phone || '',
            school: resp.data.school || '',
            gender: resp.data.gender || '',
            birthday: resp.data.birthday || ''
          };
          window.localStorage.setItem('user', JSON.stringify(_this.curUser));
        }
      });
    },
    saveUserInfo() {
      // 保存头像背景色到localStorage，保证全局同步
      let user = JSON.parse(window.localStorage.getItem('user') || '{}');
      user.avatarBgColor = this.avatarBgColor;
      // 如果没有自定义头像，则avatar设为''
      if (!this.showImageAvatar) {
        user.avatar = '';
      } else {
        user.avatar = this.curUser.avatar;
      }
      window.localStorage.setItem('user', JSON.stringify(user));
  // 补充 id 字段，优先从 curUser.id，其次从 localStorage 或 $store
  // 从 localStorage 读取 id，保证一定有值
  let userId = JSON.parse(window.localStorage.getItem('user') || '{}').userId || this.curUser.id || this.$store.state.user.id;
  // 格式化 birthday 字段为 'YYYY-MM-DD'
  let payload = { ...this.curUser, id: userId };
  if (payload.birthday && typeof payload.birthday === 'string') {
    if (payload.birthday.includes('T')) {
      const dateObj = new Date(payload.birthday);
      if (!isNaN(dateObj.getTime())) {
        const yyyy = dateObj.getFullYear();
        const mm = String(dateObj.getMonth() + 1).padStart(2, '0');
        const dd = String(dateObj.getDate()).padStart(2, '0');
        payload.birthday = `${yyyy}-${mm}-${dd}`;
      } else {
        payload.birthday = payload.birthday.slice(0, 10);
      }
    } else if (payload.birthday.length > 10) {
      payload.birthday = payload.birthday.slice(0, 10);
    }
  }
  this.$axios.put('/users/info', payload).then(resp => {
        // 响应拦截器已返回 resp.data，直接判断 resp.code
        if (resp && resp.code === 200) {
          this.$message.success("保存成功");
          // 保存成功后重新拉取后端最新数据
          this.getCurUser();
        } else {
          this.$message.error((resp && (resp.msg || resp.message)) || "保存失败");
        }
      });
    },
    getAvatarText(name) {
      if (!name) return '';
      // 中文优先，英文取首字母大写
      const firstChar = name.trim().charAt(0);
      if (/[\u0000-\u007f]/.test(firstChar)) {
        return firstChar.toUpperCase();
      } else {
        return firstChar;
      }
    },
    resetPwdForm() {
      this.pwdForm.oldPassword = '';
      this.pwdForm.newPassword = '';
    },
    handleChangePassword() {
      if (!this.pwdForm.oldPassword || !this.pwdForm.newPassword) {
        this.$message.error('请填写完整信息');
        return;
      }
      this.$axios.put('/users/changePassword', this.pwdForm).then(resp => {
        if (resp && resp.code === 200) {
          this.$message.success('密码修改成功');
          this.showChangePwd = false;
          this.resetPwdForm();
        } else {
          this.$message.error(resp.msg || '密码修改失败');
        }
      });
    },
  }
}
</script>

<style scoped>

.user-info-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 70vh;
  background: #f7f8fa;
}
.user-info-card {
  width: 600px;
  padding: 32px 24px 24px 24px;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
}
.user-info-header {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 8px;
}
.user-avatar-square {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  color: #fff;
  font-weight: bold;
  user-select: none;
  background: #409EFF;
  overflow: hidden;
}
.avatar-text {
  width: 80px;
  text-align: center;
  user-select: none;
}
.avatar-color-select {
  margin-left: 16px;
  width: 120px;
}
.user-info-form {
  margin-top: 16px;
}
.user-info-actions {
  text-align: right;
  margin-top: 16px;
}

</style>
